//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState } from "react";
import type { LocalRepoExtInfo } from "@/stores/localrepo";
import { Form, Input, message, Modal, Switch } from "antd";
import { useStores } from "@/hooks";
import type { GitFlowInfo } from "@/api/git_flow";
import { isGitFlowInit, removeGitFlowInfo, setGitFlowInfo } from "@/api/git_flow";
import { resolve } from "@tauri-apps/api/path";
import { add_branch } from "@/api/git_wrap";

export interface ConfigGitFlowModalProps {
    repoExtInfo: LocalRepoExtInfo;
    onClose: () => void;
}

const ConfigGitFlowModal = (props: ConfigGitFlowModalProps) => {
    const localRepoStore = useStores("localRepoStore");

    const [enableFlow, setEnableFlow] = useState(isGitFlowInit(props.repoExtInfo.branchList, props.repoExtInfo.gitFlowInfo));
    const [gitFlowCfg, setGitFlowCfg] = useState(props.repoExtInfo.gitFlowInfo);
    const [hasChange, setHasChange] = useState(false);

    const guessMasterBranch = () => {
        const nameList = props.repoExtInfo.branchList.map(item => item.name);
        if (nameList.includes("main")) {
            return "main";
        }
        return "master";
    };

    const isValid = () => {
        if (!enableFlow) {
            return true;
        }
        if (gitFlowCfg.masterBranch == "") {
            return false;
        }
        if (gitFlowCfg.developBranch == "") {
            return false;
        }
        if (gitFlowCfg.featurePrefix == "") {
            return false;
        }
        if (gitFlowCfg.bugfixPrefix == "") {
            return false;
        }
        if (gitFlowCfg.releasePrefix == "") {
            return false;
        }
        if (gitFlowCfg.hotfixPrefix == "") {
            return false;
        }
        if (gitFlowCfg.supportPrefix == "") {
            return false;
        }
        return true;
    };

    const configGitFlow = async () => {
        if (!enableFlow) {
            await removeGitFlowInfo(props.repoExtInfo.repoInfo.path);
            props.onClose();
            message.info("设置成功");
            localRepoStore.onUpdateRepo(props.repoExtInfo.id);
            return;
        }
        //调整配置文件
        const hooksPath = await resolve(props.repoExtInfo.repoInfo.path, ".git", "hooks");
        const tmpCfg: GitFlowInfo = {
            masterBranch: gitFlowCfg.masterBranch ?? guessMasterBranch(),
            developBranch: gitFlowCfg.developBranch ?? "develop",
            featurePrefix: gitFlowCfg.featurePrefix ?? "feature/",
            bugfixPrefix: gitFlowCfg.bugfixPrefix ?? "bugfix/",
            releasePrefix: gitFlowCfg.releasePrefix ?? "release/",
            hotfixPrefix: gitFlowCfg.hotfixPrefix ?? "hotfix/",
            supportPrefix: gitFlowCfg.supportPrefix ?? "support/",
            versionTagPrefix: gitFlowCfg.versionTagPrefix ?? "v",
            hooksPath: hooksPath,
        };
        if (tmpCfg.featurePrefix!.endsWith("/") == false) {
            tmpCfg.featurePrefix += "/";
        }
        if (tmpCfg.bugfixPrefix!.endsWith("/") == false) {
            tmpCfg.bugfixPrefix += "/";
        }
        if (tmpCfg.releasePrefix!.endsWith("/") == false) {
            tmpCfg.releasePrefix += "/";
        }
        if (tmpCfg.hotfixPrefix!.endsWith("/") == false) {
            tmpCfg.hotfixPrefix += "/";
        }
        if (tmpCfg.supportPrefix!.endsWith("/") == false) {
            tmpCfg.supportPrefix += "/";
        }
        //检查分支是否存在
        if (props.repoExtInfo.branchList.findIndex(item => item.name == tmpCfg.masterBranch) == -1) {
            await add_branch(props.repoExtInfo.repoInfo.path, tmpCfg.masterBranch!, props.repoExtInfo.headInfo.commit_id);
        }
        if (props.repoExtInfo.branchList.findIndex(item => item.name == tmpCfg.developBranch) == -1) {
            await add_branch(props.repoExtInfo.repoInfo.path, tmpCfg.developBranch!, props.repoExtInfo.headInfo.commit_id);
        }
        //写入配置
        await setGitFlowInfo(props.repoExtInfo.repoInfo.path, tmpCfg);

        props.onClose();
        message.info("设置成功");
        localRepoStore.onUpdateRepo(props.repoExtInfo.id);
    };

    return (
        <Modal open title="配置Git工作流" mask={false}
            okText="设置" okButtonProps={{ disabled: !isValid() || !hasChange }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                configGitFlow();
            }}>
            <Form labelCol={{ span: 6 }}>
                <Form.Item label="工作流">
                    <Switch checked={enableFlow} onChange={checked => {
                        setEnableFlow(checked);
                        setHasChange(true);
                    }} />
                </Form.Item>
                {enableFlow && (
                    <>
                        <Form.Item label="master分支">
                            <Input value={gitFlowCfg.masterBranch ?? guessMasterBranch()} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    masterBranch: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="develop分支">
                            <Input value={gitFlowCfg.developBranch ?? "develop"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    developBranch: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="feature分支前缀">
                            <Input value={gitFlowCfg.featurePrefix ?? "feature/"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    featurePrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="bugfix分支前缀">
                            <Input value={gitFlowCfg.bugfixPrefix ?? "bugfix/"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    bugfixPrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="release分支前缀">
                            <Input value={gitFlowCfg.releasePrefix ?? "release/"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    releasePrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="hotfix分支前缀">
                            <Input value={gitFlowCfg.hotfixPrefix ?? "hotfix/"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    hotfixPrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="support分支前缀">
                            <Input value={gitFlowCfg.supportPrefix ?? "support/"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    supportPrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                        <Form.Item label="版本标记前缀">
                            <Input value={gitFlowCfg.versionTagPrefix ?? "v"} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setGitFlowCfg({
                                    ...gitFlowCfg,
                                    versionTagPrefix: e.target.value.trim(),
                                });
                                setHasChange(true);
                            }} />
                        </Form.Item>
                    </>
                )}
            </Form>
        </Modal>
    );
};

export default ConfigGitFlowModal;